﻿using System;
using OnlineGameLibrary.Contract;
using OnlineGameLibrary.MessageEx;
using System.ServiceModel.Channels;
using System.Linq;
using System.Windows;


namespace OnlineGameLibrary.Game
{
    public abstract class GameBase
    {
        protected GameRoom GameRoom;
        protected Player CurrentPlayer;
        IPlayerDuplexChannel _serviceproxy;

        public event EventHandler<GameEndEventArgs> GameEnded;

        public GameBase(GameRoom gameroom, Player curplayer, IPlayerDuplexChannel serviceproxy)
        {
            CurrentPlayer = curplayer;
            GameRoom = gameroom;
            _serviceproxy = serviceproxy;
        }

        void serviceproxy_MessageReceivedFromServer(object sender, MessageEventArgs e)
        {
            if (GameMessageDefines.Namespace == e.Message.GetScope())
            {
                onMessageReceived(e.Message);
            }
        }

        protected void SendMessageToGameServer(Message msg)
        {
            if (_serviceproxy != null)
                this._serviceproxy.SendMessage(msg);
        }

        protected virtual void onMessageReceived(Message msg)
        {
            var players = msg.GetAudience();
            var duetime = msg.GetDueTime();

            if (players == null)
                onGameAction(duetime, msg);
            else foreach (var player in players)
                onPlayerAction(player, duetime, msg);
        }

        public virtual void onGameAction(DateTime duetime, Message msg)
        {
            if (msg.GetAction() == GameMessageDefines.GAME_END.Action)
            {
                GameEnd();

                if (this.GameEnded != null)
                {
                    var result = (GameResult)GameMessageDefines.GAME_END.GetMessage(msg).MessageBodyContent;
                    this.GameEnded(this,
                        new GameEndEventArgs
                        {
                            Result = result
                        });
                }
            }
        }

        public abstract void onPlayerAction(string PlayerID, DateTime duetime, Message message);
        public abstract void onPlayerLeave(string PlayerID);

        public virtual void GameStart()
        {
            _serviceproxy.MessageReceived += serviceproxy_MessageReceivedFromServer;
        }

        public abstract void GameEnd();

        bool isendexcuted;
        public virtual void DisposeGame()
        {
            if (!isendexcuted)
            {
                isendexcuted = true;
                _serviceproxy.MessageReceived -= serviceproxy_MessageReceivedFromServer;
                _serviceproxy = null;
            }
        }

        public abstract FrameworkElement GameUI { protected set; get; }
    }
}
